package com.xiaobias.distributed.pan.config;

import com.xiaobias.distributed.pan.db.service.BaiduUserService;
import com.xiaobias.distributed.pan.seurity.entity.BaiduUser;
import com.xiaobias.distributed.pan.seurity.service.BaiduAuth2UserService;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Profiles;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;


@EnableWebSecurity
public class MyWebSecurityConfig
        extends WebSecurityConfigurerAdapter {
    @Resource
    private BaiduUserService baiduUserService;
    @Resource
    private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> oAuth2AccessTokenResponseClient;

    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests(authReq -> authReq
                        .mvcMatchers("/oauth/**", "/error/**").permitAll()
                        .anyRequest().authenticated())
                .exceptionHandling()
                .and()
                .cors(cors -> cors.configurationSource(corsConfigurationSource()));

        http.headers().frameOptions().sameOrigin();;

        http.oauth2Login()
                .loginPage("/login").permitAll()
                .userInfoEndpoint()
                .customUserType(BaiduUser.class, "pan")
                .userService(new BaiduAuth2UserService(this.baiduUserService))
                .and()
                .tokenEndpoint()
                .accessTokenResponseClient(this.oAuth2AccessTokenResponseClient);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "Post", "PUT", "DELETE", "OPTIONS"));
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addExposedHeader("X-Authenticate");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

}